using System;
using System.Web.UI;
using Blazing.Web.Util;
using Blazing.BusinessObjects.Cms;

namespace Blazing.Web.Controls.Webparts
{
    [Themeable(true)]
    public class ContentWebpart : UserControl
    {
        #region Private Variables;
        bool? _active = true;
        CmsManager _manager = null;
        LiteralControl literal = null;
        #endregion

        #region Properties
        public CmsManager Manager
        {
            get
            {
                if(_manager == null)
                    _manager = Blazing.Util.CmsManagerHelper.FindManagerObject(Page.Controls);
                if (_manager == null)
                    throw new ApplicationException("There was no active CmsManager object found on the current page.");
                return _manager;
            }
        }

        public bool? Active
        {
            get { return _active; }
            set { _active = value; }
        }

        #endregion

        public ContentWebpart() 
        {
            _active = true;            
        }

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            literal = new LiteralControl();
            literal.ID = "PageContent";
            Contentpage retPage = null;

            if (Manager.PageId != null)
            {
                retPage = CmsFacade.GetPageById(Manager.PageId.Value);
            }
            else if (!string.IsNullOrEmpty(Manager.Url))
            {
                retPage = CmsFacade.GetPageByPermalink(Manager.SiteId.Value, Manager.Url);
            }
            
            if(retPage == null)
            {
                literal.Text = "[No Content Found]";
            }
            else
            {
                string pageText = retPage.Content;
                pageText = UrlFormatter.FormatUrlsInText(pageText);
                pageText = UrlFormatter.FormatWidgetsInText(pageText, Page, this);

                literal.Text = pageText;
            }

            this.Controls.Add(literal);
        }
    }
}
